<template>
  <div class="yhq">
    <div class="phone">
      <div class="phoneTop">
        <!-- <span class="phoneTopspan">菠萝币券</span> -->
      </div>
      <div class="coupon"
        style="
          background: linear-gradient(0deg, rgb(254, 98, 99), rgb(254, 49, 78));
        ">
        <div class="couponHead">
          <span class="couponHeadTitle">{{ ruleForm.couponName }}</span>
          <a class="couponShare">分享</a>
        </div>
        <div style="
            color: #fff;
            font-size: 30px;
            text-align: center;
            margin: 0 0 20px 0;
          "
          v-if="ruleForm.couponAmountStr">
          {{ ruleForm.couponAmountStr }}菠萝币券
        </div>

        <!-- <div v-if="ruleForm.isshow == true" style="color: #fff; font-size: 14px; text-align: center">
          满任意金额可用
        </div> -->
        <!-- <div v-if="ruleForm.isshow == false && ruleForm.baseAmountStr > 0"
          style="color: #fff; font-size: 14px; text-align: center">
          满{{ ruleForm.baseAmountStr }}元可用
        </div> -->
        <div v-if="ruleForm.startDate"
          style="
            font-size: 14px;
            margin-top: 15px;
            color: hsla(0, 0%, 100%, 0.5);
          ">
          有效日期：{{ ruleForm.startDate }} 到 {{ ruleForm.endDate }}
        </div>
      </div>
      <div class="couponbottom"></div>
      <p class="instructions">使用说明</p>
      <div class="instructionsTitle">
        <div>{{ ruleForm.couponName }}</div>
        <div style="margin: 10px 0"
          v-if="ruleForm.startDate">
          活动时间：{{ ruleForm.startDate }} 到 {{ ruleForm.endDate }}
        </div>
        <div v-if="ruleForm.couponName">
          菠萝币数量：<span v-if="ruleForm.checkProduct == 0">全部</span><span v-else>部分</span>商品可用
          <span>可兑换{{ ruleForm.couponAmountStr }}菠萝币</span><span v-if="ruleForm.couponAmountStr">，{{ ruleForm.couponAmountStr }}菠萝币券</span>
        </div>
      </div>
    </div>

    <!-- 表单 -->
    <div class="formdata">
      <div class="setup big_title_style">基本设置</div>
      <el-form :model="ruleForm"
        ref="ruleForm"
        label-width="110px"
        :rules="rules">
        <el-form-item label="菠萝币券图标"
          prop="couponIconUrl">
          <imageArraySize :imageStr.sync="ruleForm.couponIconUrl"
            :key="ruleForm.couponIconUrl"
            :msg="'图片要求：大小1MB以内。'"
            :limit="1"
            ref="childss">
          </imageArraySize>
        </el-form-item>
        <el-form-item label="菠萝币券名称"
          prop="couponName">
          <el-input v-model="ruleForm.couponName"
            placeholder="请输入菠萝币券名称"
            clearable
            maxlength="15"
            show-word-limit>
          </el-input>
        </el-form-item>
        <el-form-item label="菠萝币券描述">
          <el-input v-model="ruleForm.couponDesc"
            placeholder="请输入菠萝币券描述"
            clearable
            maxlength="25"
            show-word-limit>
          </el-input>
        </el-form-item>
        <el-form-item label="菠萝币券数量"
          prop="couponNums">
          <el-input v-model="ruleForm.couponNums"
            oninput="value=value.replace(/[^\d]/g,'')"
            placeholder="请输入数字"
            clearable
            maxlength="7"
            show-word-limit></el-input>
          <div class="couponNumsDiv">张</div>
        </el-form-item>
        <!-- <el-form-item label="适用商品" required>
          <el-radio
            style="margin-top: 12px"
            v-model="ruleForm.checkProduct"
            label="0"
            >全部商品可用 (推荐)</el-radio
          >
          <el-radio
            style="margin-top: 15px"
            v-model="ruleForm.checkProduct"
            label="1"
            >指定商品可用</el-radio
          >
          <a
            v-if="ruleForm.checkProduct == 1"
            style="color: #155bd4"
            @click="selectCommodity"
            >选择商品</a
          >
         已选商品表格组件 
          <selected
            ref="child"
            v-if="selectedData.length > 0"
            :selectedData="selectedData"
          ></selected>
        </el-form-item> -->
        <!-- <el-form-item label="使用门槛" required>
          <el-radio style="margin-top: 12px" v-model="ruleForm.checkBaseAmount" label="0"
            @change="ruleForm.isshow = true">无使用门槛
          </el-radio>

          <el-radio style="margin-top: 15px" v-model="ruleForm.checkBaseAmount" label="1"
            @change="ruleForm.isshow = false">订单满<el-input v-model="ruleForm.baseAmountStr" maxlength="8"
              @input="ruleForm.baseAmountStr = oninput(ruleForm.baseAmountStr, 2)"
              :disabled="ruleForm.checkBaseAmount != '1' " style="width: 110px; margin: 0 10px"></el-input>
            <div class="baseAmountDiv">元</div>
            <span style="position: relative; right: 35px">可用</span>
          </el-radio>
        </el-form-item> -->

        <el-form-item label="适用门店"
          required>
          <el-radio style="margin-top: 12px"
            v-model="ruleForm.checkStore"
            label="0">全部门店可用 (推荐)</el-radio>
          <el-radio style="margin-top: 15px"
            v-model="ruleForm.checkStore"
            label="1">指定门店可用</el-radio>
          <a v-if="ruleForm.checkStore == 1"
            style="color: #155bd4"
            @click="selectCommodityA">选择门店</a>

          <!-- 已选商品表格组件 -->
          <selectedA ref="childs"
            v-if="selectedDataStore.length > 0"
            :selectedData="selectedDataStore"></selectedA>
        </el-form-item>

        <el-form-item label="菠萝币数量"
          prop="couponAmount">
          <!-- <span style="margin-right: 10px; color: #606266">减免</span> -->
          <el-input style="width: 110px"
            v-model="ruleForm.couponAmount"
            maxlength="6"
            show-word-limit
            @input="
              ruleForm.couponAmountStr = oninput(ruleForm.couponAmountStr, 2)
            "></el-input>
          <div class="couponAmountDiv">个</div>

          <p style="
              font-size: 12px;
              color: #969799;
              line-height: 15px;
              width: 390px;
              margin-top: 10px;
            ">
            优惠内容是商家单独给消费者的优惠金额，设置大额优惠金额时需谨慎，以免造成资损（测试活动建议设置小额优惠内容）。
          </p>
        </el-form-item>

        <commodityStore v-if="storeOpen"
          @toCloseBox="toCloseBox"
          @multipleSelection="multipleSelectionA"
          :flag="storeOpen"
          :source="false"
          ref="selTables"></commodityStore>

        <el-form-item label="用券时间"
          prop="expireDays">
          <el-radio v-model="ruleForm.checkTime"
            label="0"
            @change="ischecktime(ruleForm.checkTime)">
            <!-- v-if="ruleForm.checkTime == '0'"
              :disabled="true" -->
            <el-date-picker v-model="timeValue"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="getSTime">
            </el-date-picker>
            <!-- <div>1234</div> -->
          </el-radio>
          <el-radio style="margin-top: 15px"
            v-model="ruleForm.checkTime"
            label="1"
            @change="ischecktime(ruleForm.checkTime)">
            领券当日起<el-input style="width: 120px; margin: 0 10px"
              v-model="ruleForm.expireDays"
              :disabled="ruleForm.checkTime != '1'"
              maxlength="3"
              show-word-limit
              oninput="value=value.replace(/[^\d]/g,'')"
              placeholder="请输入数字">
            </el-input>天内可用
          </el-radio>
          <p style="
              font-size: 12px;
              color: #969799;
              line-height: 15px;
              width: 390px;
              margin-top: 10px;
            ">
            若设置固定用券时间，编辑保存后对已领取未使用及后续领取的券均生效。若设置领券当日/次日n天内可用，编辑保存后仅对后续领取的券生效
          </p>
        </el-form-item>
      </el-form>
    </div>
    <div class="yhqBottom">
      <el-button type="primary"
        style="color: #fff"
        @click="preservation">保存</el-button>
      <el-button @click="close()">取消</el-button>
    </div>

    <!-- <el-dialog v-if="ruleForm.open" title="选择商品" :visible.sync="ruleForm.open" width="800px" append-to-body @close="closeDialog()"> -->
    <commoditytab v-if="open"
      @toCloseBox="toCloseBox"
      @multipleSelection="multipleSelection"
      :flag="open"
      :proUids="proUids"
      ref="selTable"></commoditytab>

    <!-- </el-dialog> -->

  </div>
</template>
<script>
import { getCoupon, addCoupon, updateCoupon } from "@/api/activity/coupon";
import commoditytab from "@/components/Activity/commodityTab";
import selected from "@/components/Activity/SelectedProducts";
import imageArraySize from "@/components/ImageUpload/imageArraySize";
import selectedA from "@/components/Activity/SelectedStore";
import commodityStore from "@/components/Activity/commodityStore";
export default {
  components: {
    commoditytab,
    selected,
    selectedA,
    imageArraySize, commodityStore
  },
  data () {
    return {
      selectedDataStore: [],
      subFlag: true,
      proUids: [], //排除商品，活动用到
      selectedData: [],
      timeValue: [],
      open: false,
      storeOpen: false,
      deviceOpen: false,
      itemUid: this.$route.params.itemId,
      ruleForm: {
        couponUid: null,
        couponIconUrl: "",
        couponName: "",
        couponDesc: "",
        couponType: "3",
        couponNums: 0,
        couponAmount: 0,
        baseAmount: 1,
        couponAmountStr: 0,
        baseAmountStr: 0,
        startDate: "",
        endDate: "",
        expireType: "",
        expireDays: "",
        couponProUids: null,
        isshow: true,
        checkTime: "0",
        checkProduct: "0",
        checkStore: "0",
        checkBaseAmount: "0",
      },

      rules: {
        couponName: [
          {
            required: true,
            message: "不能为空",
            trigger: "blur",
          },
        ],
        couponAmount: [
          {
            required: true,
            message: "不能为空",
            trigger: "blur",
          },
        ],
        couponNums: [
          {
            required: true,
            message: "不能为空",
            trigger: "blur",
          },
        ],
        expireDays: [
          {
            required: true,
            message: "不能为空",
            trigger: "blur",
          },
        ],
        startDate: [
          {
            required: true,
            message: "不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created () {
    this.getCoupon();
  },
  methods: {
    getCoupon () {
      let $this = this;
      const couponUid = $this.$route.params && $this.$route.params.couponUid;
      if (couponUid) {
        getCoupon(couponUid).then((response) => {
          var d = response.data;
          $this.ruleForm = d;
          $this.ruleForm.baseAmountStr = parseFloat(d.baseAmountStr);
          $this.ruleForm.couponAmountStr = parseFloat(d.couponAmountStr);
          if (d.proList) {
            $this.selectedData = d.proList;
          }
          if (d.checkBaseAmount == "1") {
            $this.ruleForm.isshow = false;
          } else {
            $this.ruleForm.isshow = true;
          }
          $this.timeValue.push($this.ruleForm.startDate);
          $this.timeValue.push($this.ruleForm.endDate);
        });
      }
    },

    toCloseBox () {
      this.storeOpen = false;
    },

    multipleSelectionA (data) {
      this.storeOpen = false
      this.selectedDataStore = data;
      this.$nextTick(() => {
        ///this.$refs.childStore.getList();
      });
    },

    ischecktime (v) {
      //清除之前的校验
      this.$refs.ruleForm.clearValidate();
      this.ruleForm.expireDays = "";
      console.log(this.ruleForm);
      if (v == "0" && this.timeValue && this.timeValue.length > 0)
        this.ruleForm.expireDays = "0";
      this.timeValue = [];

    },
    //提交保存
    preservation () {
      let proUids = null;
      if (this.selectedData) {
        proUids = "";
        this.selectedData.forEach((d) => {
          proUids += d.productUid + ",";
        });
      }
      this.ruleForm.couponProUids = proUids;
      //图片上传组件需要定义
      this.$refs.childss.selectImgs();

      this.$refs["ruleForm"].validate((valid) => {
        if (valid && this.subFlag) {
          if (
            this.ruleForm.checkTime &&
            this.ruleForm.checkTime == "1" &&
            this.ruleForm.expireDays == "0"
          ) {
            return this.msgError("用劵天数需大于0");
          }
          this.ruleForm.baseAmount = parseInt(
            parseFloat(this.ruleForm.baseAmountStr) * 100
          );
          this.ruleForm.couponAmount = parseInt(
            parseFloat(this.ruleForm.couponAmountStr) * 100
          );

          console.log(this.ruleForm);
          const couponUid = this.$route.params && this.$route.params.couponUid;
          if (couponUid) {
            this.ruleForm.couponUid = couponUid;
            updateCoupon(this.ruleForm).then((respone) => {
              this.msgSuccess("修改成功");
              this.close();
              // this.$router.go(-1);
            });
          } else {
            addCoupon(this.ruleForm).then((respone) => {
              this.msgSuccess("添加成功");
              this.close();
              // this.$router.go(-1);
            });
          }
          this.subFlag = false;
        }
      });
    },

    /** 关闭按钮 */
    close () {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push({
        path: "/centre/coupon/couponManager",
        query: {
          t: Date.now(),
        },
      });
    },
    multipleSelection (data) {
      this.open = false;
      this.selectedData = data;
      this.$nextTick(() => {
        this.$refs.child.getList();
      });
    },
    toCloseBox () {
      this.open = false;
    },

    selectCommodityA () {
      this.$forceUpdate()
      this.storeOpen = true;
      this.$nextTick(() => {
        this.$refs["selTables"].greet(this.selectedDataStore);
      });
    },

    //调用子组件中方法，向子组件传值
    selectCommodity () {
      this.$forceUpdate();
      this.open = true;
      this.$nextTick(() => {
        this.$refs["selTable"].greet(this.selectedData);
      });
    },
    p (s) {
      return s < 10 ? "0" + s : s;
    },
    getSTime (val) {
      if (val) {
        //手动赋值，使其通过校验
        this.ruleForm.expireDays = "0";
        const d = new Date(val[0]);
        const resDate =
          d.getFullYear() +
          "-" +
          this.p(d.getMonth() + 1) +
          "-" +
          this.p(d.getDate());
        const resTime =
          this.p(d.getHours()) +
          ":" +
          this.p(d.getMinutes()) +
          ":" +
          this.p(d.getSeconds());
        this.ruleForm.startDate = resDate + " " + resTime;
        const c = new Date(val[1]);
        const resDatec =
          c.getFullYear() +
          "-" +
          this.p(c.getMonth() + 1) +
          "-" +
          this.p(c.getDate());
        const resTimec =
          this.p(c.getHours()) +
          ":" +
          this.p(c.getMinutes()) +
          ":" +
          this.p(c.getSeconds());
        this.ruleForm.endDate = resDatec + " " + resTimec;
      } else {
        this.ruleForm.startDate = null;
        this.ruleForm.endDate = null;
      }

    },

    baseAmount0 () {
      this.ruleForm.isshow = true;
    },
    baseAmount1 () {
      this.ruleForm.isshow = false;
    },
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert("submit!");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm (formName) {
      this.$refs[formName].resetFields();
    },
    closeDialog () {
      this.open = false;
      console.log(this.ruleForm.open);
    },
    oninput (num, limit) {
      var str = num;
      var len1 = str.substr(0, 1);
      var len2 = str.substr(1, 1);
      if (str.length > 1 && len1 == 0 && len2 != ".") {
        str = str.substr(1, 1);
      }
      if (len1 == ".") {
        str = "";
      }
      if (str.indexOf(".") != -1) {
        var str_ = str.substr(str.indexOf(".") + 1);
        if (str_.indexOf(".") != -1) {
          str = str.substr(0, str.indexOf(".") + str_.indexOf(".") + 1);
        }
      }
      //正则替换
      str = str.replace(/[^\d^\.]+/g, ""); // 保留数字和小数点
      if (limit / 1 === 1) {
        str = str.replace(/^\D*([0-9]\d*\.?\d{0,1})?.*$/, "$1"); // 小数点后只能输 1 位
      } else {
        str = str.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, "$1"); // 小数点后只能输 2 位
      }
      return str;
    },
  },
};
</script>
<style lang="less" scoped>
::v-deep .el-range-editor.is-disabled {
  border-color: #e4e7ed !important;
}
.yhq {
  display: flex;
  justify-content: center;
  padding-top: 30px;
  width: 100%;
  height: 100%;

  .phone {
    width: 360px;
    height: 580px;
    background-color: #f9f9f9;
    border: 1px solid #ccc;

    .phoneTop {
      width: 100%;
      height: 60px;
      background-image: url(../../../assets/images/phoneTops.png);
      background-repeat: no-repeat;
      background-size: 100% 100%;

      .phoneTopspan {
        color: #fff;
        position: relative;
        left: 42%;
        top: 44%;
        transform: translate(-50%, -50%);
        font-size: 18px;
        font-weight: bolder;
      }
    }

    .couponTitle {
      color: #ccc;
      height: 15px;
      line-height: 15px;
      text-align: center;
    }

    .coupon {
      width: 100%;
      height: 180px;

      .couponHead {
        width: 100%;
        position: relative;

        .couponHeadTitle {
          font-size: 18px;
          line-height: 55px;
          max-width: 290px;
          color: #fff;
          margin-left: 10px;
        }

        .couponShare {
          border: 1px solid #ffbabb;
          border-color: hsla(0, 0%, 100%, 0.5);
          border-radius: 4px;
          color: hsla(0, 0%, 100%, 0.5);
          cursor: pointer;
          height: 30px;
          line-height: 30px;
          text-align: center;
          width: 50px;
          position: absolute;
          top: 10px;
          right: 10px;
          font-weight: bold;
          font-size: 15px;
        }
      }
    }

    .couponbottom {
      background-size: 15px 15px;
      -webkit-clip-path: inset(0 0 2px 0);
      clip-path: inset(0 0 2px 0);
      content: " ";
      display: block;
      height: 10px;
      background-image: radial-gradient(
        rgb(249, 249, 249) 0px,
        rgb(249, 249, 249) 5px,
        rgb(254, 98, 99) 5px,
        rgb(254, 98, 99) 100%
      );
    }

    .instructions {
      color: #333;
      padding-left: 10px;
      font-size: 15px;
      font-weight: bold;
      margin: 5px 0;
    }

    .instructionsTitle {
      background: #fff;
      border-bottom: 1px solid #e5e5e5;
      border-top: 1px solid #e5e5e5;
      color: #333;
      font-size: 14px;
      line-height: 1.5;
      width: 100%;
      height: 140px;
      max-height: 200px;
      min-height: 22px;
      overflow: hidden;
      padding: 10px;
      text-overflow: ellipsis;
      white-space: pre-line;
      word-break: break-word;
    }
  }

  .formdata {
    width: 720px;
    height: 100%;
    overflow-y: auto;
    margin-left: 100px;
    background-color: #fff;
    padding: 20px 20px 68px 20px;
    border-radius: 10px;
    border: 1px solid #eee;

    .setup {
      border-bottom: 1px solid #ebedf0;
      font-size: 18px;
      padding-bottom: 8px;
      margin-bottom: 24px;
    }

    .couponNumsDiv {
      background-color: var(--theme-stroke-8, #f7f8fa);
      color: #646566;
      display: inline-block;
      height: 32px;
      line-height: 32px;
      padding: 0 9px;
      box-sizing: border-box;
      vertical-align: middle;
      font-size: 14px;
      position: relative;
      right: 34px;
      top: -1px;
      border-left: 1px solid #dcdee0;
    }

    .baseAmountDiv {
      background-color: var(--theme-stroke-8, #f7f8fa);
      color: #646566;
      display: inline-block;
      height: 32px;
      line-height: 32px;
      padding: 0 9px;
      box-sizing: border-box;
      vertical-align: middle;
      font-size: 14px;
      position: relative;
      right: 44px;
      top: -2px;
      border-left: 1px solid #dcdee0;
    }

    .couponAmountDiv {
      background-color: var(--theme-stroke-8, #f7f8fa);
      color: #646566;
      display: inline-block;
      height: 32px;
      line-height: 32px;
      padding: 0 9px;
      box-sizing: border-box;
      vertical-align: middle;
      font-size: 14px;
      position: relative;
      right: 34px;
      top: -2px;
      border-left: 1px solid #dcdee0;
    }
  }

  .el-input {
    width: 240px;
  }

  /deep/ .el-radio {
    display: block;

    white-space: normal;
    margin-right: 0;
  }

  .yhqBottom {
    position: fixed;
    bottom: 0;
    z-index: 10;
    left: 0;
    width: 100%;
    height: 68px;
    padding-left: 120px;
    box-shadow: 0 -2px 8px rgb(200 201 204 / 20%);
    display: flex;
    align-items: center;
    justify-content: center;
    background: #fff;
  }
}
</style>
